package org.xshaokuang.loginandemail.login;

import cn.nukkit.Player;
import cn.nukkit.utils.Config;
import java.util.HashMap;
import java.util.Map;
import java.security.MessageDigest;

public class LoginDataManager {
    private final Map<String, LoginData> userDataMap = new HashMap<>();
    private final Config config;

    public LoginDataManager(Config config) {
        this.config = config;
    }

    public boolean has(String playerName)  {
        return userDataMap.containsKey(playerName);
    }

    public void loadFromConfig(String playerName) {
        if(config.exists(playerName)) {
            LoginData data = new LoginData(
                    playerName,
                    config.getString(playerName + ".password"),
                    config.getLong(playerName + ".login_time"),
                    config.getString(playerName + ".ip"),
                    config.getString(playerName + ".QQ")
            );
            userDataMap.put(playerName, data);
        }
        }

    public void remove(String playerName) {
        userDataMap.remove(playerName);
    }

    public void saveToConfig(String playerName) {
        LoginData data = userDataMap.get(playerName);
        config.set(playerName + ".password", data.getPassword());
        config.set(playerName + ".login_time", data.getLoginTime());
        config.set(playerName + ".ip", data.getIp());
        config.set(playerName + ".QQ", data.getQQ());
        config.save();
    }

    public void saveAllToConfig() {
        userDataMap.forEach((name, data) -> {
            config.set(name + ".password", data.getPassword());
            config.set(name + ".login_time", data.getLoginTime());
            config.set(name + ".ip", data.getIp());
            config.set(name + ".QQ", data.getQQ());
        });
        config.save();
    }

    public boolean needsLogin(String playerName, String currentIp) {
        LoginData data = userDataMap.get(playerName);
        if (data == null) return true;

        long timeDiff = System.currentTimeMillis() - data.getLoginTime();
        return timeDiff > 86400000 || !data.getIp().equals(currentIp);
    }

    public void addOrUpdatePlayer(String playerName, String password, String ip, String QQ) {
        LoginData existing = userDataMap.get(playerName);
        if (existing != null) {
            existing.updateLoginInfo(System.currentTimeMillis(), ip);
        } else {
            String hashed = md5(password);
            userDataMap.put(playerName, new LoginData(
                    playerName,
                    hashed,
                    System.currentTimeMillis(),
                    ip,
                    QQ // 默认QQ号
            ));
        }
        saveToConfig(playerName);
    }

    public void upDateTimeAndIp(Player player) {
        String playerName = player.getName();
        LoginData existing = userDataMap.get(playerName);
        if (existing != null) {
            existing.updateLoginInfo(System.currentTimeMillis(), player.getAddress());
            }
        saveToConfig(player.getName());
    }

    public boolean validatePassword(String playerName, String input) {
        LoginData data = userDataMap.get(playerName);
        return data != null && data.getPassword().equals(md5(input));
    }

    private String md5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] hash = md.digest(input.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : hash) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (Exception e) {
            throw new RuntimeException("MD5加密错误");
        }
    }
}

